﻿using System;
using System.Net;
using System.IO;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
using System.Text.RegularExpressions;

namespace QD.WX.Utill
{
    /// <summary>
    /// 发送Web远程请求类
    /// </summary>
    public class WebRequestHelper
    {
        public static string Referer = "";
        public static ICredentials Credentials = null;
        public static CookieContainer m_Cookie = new CookieContainer();
        public static CookieContainer bd_Cookie = null;
        public static Uri ResponseUri { get; set; }
        public WebRequestHelper()
        {
        }
        public static void Reset(int days)
        {
            bd_Cookie = new CookieContainer();
            string url = "http://www.baidu.com";
            Cookie cookie = new Cookie("BAIDUID", "2D5463F3529D42AAE40FFF3B14E6DB51");
            cookie.Domain = ".baidu.com";
            cookie.Expires = DateTime.Now.AddDays(days);
            bd_Cookie.Add(new Uri(url), cookie);

            //m_Cookie.Add(new Uri(url), new Cookie("BAIDUID", "2D5463F3529D42AAE40FFF3B14E6DB51"));

            //m_Cookie.Add(new Uri(url), new Cookie("BAIDUPSID", "2D5463F3529D42AAE40FFF3B14E6DB51"));
            //m_Cookie.Add(new Uri(url), new Cookie("locale", "zh"));
            //m_Cookie.Add(new Uri(url), new Cookie("BD_CK_SAM", "1"));
            //m_Cookie.Add(new Uri(url), new Cookie("BD_HOME", "0"));
            //m_Cookie.Add(new Uri(url), new Cookie("BD_UPN", "12314653"));
        }

        public static string Request(string url, bool isFirst, Cookie ck1, out string html)
        {

            html = "";
            StreamReader sr = null;
            HttpWebRequest myRequest = null;
            HttpWebResponse myResponse = null;

            try
            {
                Referer = "https://www.baidu.com";
                //构造Web请求
                if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase))
                {
                    ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
                    myRequest = WebRequest.Create(url) as HttpWebRequest;
                    myRequest.ProtocolVersion = HttpVersion.Version10;
                }
                else
                    myRequest = (HttpWebRequest)WebRequest.Create(url);
                //myRequest.UserAgent = "Mozilla/5.0 (Windows NT 5.2) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.97 Safari/537.11";
                myRequest.Referer = Referer;
                myRequest.Headers.Add("Accept-Language", "zh-cn");
                myRequest.KeepAlive = true;
                myRequest.Timeout = 10000;
                myRequest.ServicePoint.Expect100Continue = false;

                //if (bd_Cookie == null)
                //    Reset(1);
                //myRequest.CookieContainer = bd_Cookie;

                bd_Cookie = new CookieContainer();
                Random rand = new Random();

                //Cookie ck1 = new Cookie("BAIDUID", "2D5463F3529D42AAE40FFF3B14E6DB" + rand.Next(10, 99).ToString());
                //Cookie ck1 = new Cookie("BAIDUID", GUID+":FG=1");



                ck1.Domain = ".baidu.com";
                bd_Cookie.Add(ck1);
                myRequest.CookieContainer = bd_Cookie;
                if (Credentials == null)
                    Credentials = CredentialCache.DefaultCredentials;
                myRequest.Credentials = Credentials;


                myResponse = (HttpWebResponse)myRequest.GetResponse();
                string cookieheader = myRequest.CookieContainer.GetCookieHeader(new Uri(url));
                m_Cookie.SetCookies(new Uri(url), cookieheader);
                sr = new StreamReader(myResponse.GetResponseStream(), System.Text.Encoding.GetEncoding("UTF-8"));
                html = sr.ReadToEnd();

            }
            catch (System.Net.WebException ex)
            {
                html = ex.Message + "verify.baidu";
                return ex.Message;
            }
            catch (Exception ex)
            {
                html = "";
                return ex.Message;
            }
            finally
            {
                if (sr != null)
                    sr.Close();

                if (myResponse != null)
                    myResponse.Close();

                if (myRequest != null)
                    myRequest.Abort();
            }
            return "";
        }
        public static string Requestcookie(string url, bool isFirst, Cookie ck1, out string html)
        {

            html = "";
            StreamReader sr = null;
            HttpWebRequest myRequest = null;
            HttpWebResponse myResponse = null;

            try
            {
                Referer = "https://www.baidu.com";
                //构造Web请求
                if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase))
                {
                    ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
                    myRequest = WebRequest.Create(url) as HttpWebRequest;
                    myRequest.ProtocolVersion = HttpVersion.Version10;
                }
                else
                    myRequest = (HttpWebRequest)WebRequest.Create(url);
                //myRequest.UserAgent = "Mozilla/5.0 (Windows NT 5.2) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.97 Safari/537.11";
                myRequest.Referer = Referer;
                myRequest.Headers.Add("Accept-Language", "zh-cn");
                myRequest.KeepAlive = true;
                myRequest.Timeout = 10000;
                myRequest.ServicePoint.Expect100Continue = false;

                //if (bd_Cookie == null)
                //    Reset(1);
                //myRequest.CookieContainer = bd_Cookie;

                bd_Cookie = new CookieContainer();
                Random rand = new Random();

                //Cookie ck1 = new Cookie("BAIDUID", "2D5463F3529D42AAE40FFF3B14E6DB" + rand.Next(10, 99).ToString());
                //Cookie ck1 = new Cookie("BAIDUID", GUID+":FG=1");



                ck1.Domain = ".baidu.com";
                bd_Cookie.Add(ck1);
                myRequest.CookieContainer = bd_Cookie;
                if (Credentials == null)
                    Credentials = CredentialCache.DefaultCredentials;
                myRequest.Credentials = Credentials;


                myResponse = (HttpWebResponse)myRequest.GetResponse();
                string cookieheader = myRequest.CookieContainer.GetCookieHeader(new Uri(url));
                m_Cookie.SetCookies(new Uri(url), cookieheader);
                sr = new StreamReader(myResponse.GetResponseStream(), System.Text.Encoding.GetEncoding("UTF-8"));
                html = sr.ReadToEnd();
                Regex ri = new Regex("BAIDUID=([\\s\\S].*?);", RegexOptions.IgnoreCase);
                if (ri.IsMatch(cookieheader.ToString()))
                {
                    html = ri.Match(cookieheader.ToString()).Groups[1].Value;
                }

            }
            catch (System.Net.WebException ex)
            {
                
                html = ex.Message + "verify.baidu";
                return ex.Message;
            }
            catch (Exception ex)
            {
                
                html = "";
                return ex.Message;
            }
            finally
            {
                if (sr != null)
                    sr.Close();

                if (myResponse != null)
                    myResponse.Close();

                if (myRequest != null)
                    myRequest.Abort();
            }
            return "";
        }


        /// <summary>
        /// 发送Get远程请求，返回UTF-8编码的响应流
        /// </summary>
        /// <param name="url">格式：http://www,03you.com/login.aspx?username=test&pwd=123</param>
        /// <param name="html"></param>
        /// <returns></returns>
        public static string Request(string url, bool isFirst, out string html)
        {

            html = "";
            StreamReader sr = null;
            HttpWebRequest myRequest = null;
            HttpWebResponse myResponse = null;

            try
            {
                Referer = "https://www.baidu.com";
                //构造Web请求
                if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase))
                {
                    ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
                    myRequest = WebRequest.Create(url) as HttpWebRequest;
                    myRequest.ProtocolVersion = HttpVersion.Version10;
                }
                else
                    myRequest = (HttpWebRequest)WebRequest.Create(url);
                //myRequest.UserAgent = "Mozilla/5.0 (Windows NT 5.2) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.97 Safari/537.11";
                myRequest.Referer = Referer;
                myRequest.Headers.Add("Accept-Language", "zh-cn");
                myRequest.KeepAlive = true;
                myRequest.Timeout = 10000;
                myRequest.ServicePoint.Expect100Continue = false;

                //if (bd_Cookie == null)
                //    Reset(1);
                //myRequest.CookieContainer = bd_Cookie;

                bd_Cookie = new CookieContainer();
                Random rand = new Random();
                string GUID = System.Guid.NewGuid().ToString().Replace("-", "").ToUpper();
                Cookie ck1 = new Cookie("BAIDUID", "2D5463F3529D42AAE40FFF3B14E6DB" + rand.Next(10, 99).ToString());
                //Cookie ck1 = new Cookie("BAIDUID", GUID+":FG=1");


                ck1.Domain = ".baidu.com";
                bd_Cookie.Add(ck1);
                myRequest.CookieContainer = bd_Cookie;
                if (Credentials == null)
                    Credentials = CredentialCache.DefaultCredentials;
                myRequest.Credentials = Credentials;


                myResponse = (HttpWebResponse)myRequest.GetResponse();
                string cookieheader = myRequest.CookieContainer.GetCookieHeader(new Uri(url));
                m_Cookie.SetCookies(new Uri(url), cookieheader);
                sr = new StreamReader(myResponse.GetResponseStream(), System.Text.Encoding.GetEncoding("UTF-8"));
                html = sr.ReadToEnd();
            }
            catch (System.Net.WebException ex)
            {
                html = ex.Message + "verify.baidu";
                return ex.Message;
            }
            catch (Exception ex)
            {
                html = "";
                return ex.Message;
            }
            finally
            {
                if (sr != null)
                    sr.Close();

                if (myResponse != null)
                    myResponse.Close();

                if (myRequest != null)
                    myRequest.Abort();
            }
            return "";
        }

        /// <summary>
        /// 发送POST远程请求，返回UTF-8编码的响应流
        /// </summary>
        /// <param name="url"></param>
        /// <param name="param">post请求参数,格式如：UrlEncode("参数一")=UrlEncode("值一") &UrlEncode("参数二")=UrlEncode("值二")</param>
        /// <param name="html">请求返回值</param>
        /// <returns>错误消息</returns>
        public static string Request(string url, string param, out string html)
        {
            HttpWebRequest myRequest = null;
            HttpWebResponse myResponse = null;
            Stream reqStream = null;
            StreamReader sRead = null;
            html = "";
            byte[] data = System.Text.Encoding.GetEncoding("UTF-8").GetBytes(param);
            try
            {
                //构造Web请求

                if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase))
                {
                    ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
                    myRequest = WebRequest.Create(url) as HttpWebRequest;
                    myRequest.ProtocolVersion = HttpVersion.Version10;
                }
                else
                    myRequest = (HttpWebRequest)WebRequest.Create(url);
                myRequest.Method = "POST";
                myRequest.KeepAlive = true;
                //myRequest.ContentType = "application/octet-stream";
                myRequest.ContentType = "application/x-www-form-urlencoded;charset=utf-8";
                myRequest.ContentLength = data.Length;
                myRequest.Timeout = 10000;
                myRequest.CookieContainer = m_Cookie;

                //myRequest.UserAgent = User-Agent: Mozilla/5.0 (Windows NT 5.2) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.97 Safari/537.11
                //myRequest.Referer = Referer;

                //请求流,发送POST参数
                if (data.Length > 0)
                {
                    reqStream = myRequest.GetRequestStream();
                    reqStream.Write(data, 0, data.Length);
                    reqStream.Close();
                }
                //响应流
                myResponse = (HttpWebResponse)myRequest.GetResponse();
                string cookieheader = myRequest.CookieContainer.GetCookieHeader(new Uri(url));
                m_Cookie.SetCookies(new Uri(url), cookieheader);
                sRead = new StreamReader(myResponse.GetResponseStream(), System.Text.Encoding.GetEncoding("UTF-8"));
                html = sRead.ReadToEnd();
            }
            catch (Exception ex)
            {
                html = "";
                return ex.Message;
            }
            finally
            {
                if (sRead != null)
                    sRead.Close();

                if (reqStream != null)
                    reqStream.Close();

                if (myResponse != null)
                    myResponse.Close();

                if (myRequest != null)
                    myRequest.Abort();
            }
            return "";
        }


        public static string RequsetGet(string url, out string html)
        {
            HttpWebRequest myRequest = null;
            HttpWebResponse myResponse = null;
            Stream reqStream = null;
            StreamReader sRead = null;
            html = "";

            try
            {
                //构造Web请求
                if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase))
                {
                    ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
                    myRequest = WebRequest.Create(url) as HttpWebRequest;
                    myRequest.ProtocolVersion = HttpVersion.Version10;
                }
                else
                    myRequest = (HttpWebRequest)WebRequest.Create(url);
                myRequest.Method = "GET";
                myRequest.KeepAlive = true;
                myRequest.ContentLength = 0;
                myRequest.Timeout = 10000;
                myRequest.CookieContainer = m_Cookie;
                myRequest.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8";
                myRequest.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36";
                //myRequest.Referer = Referer;


                //响应流
                myResponse = (HttpWebResponse)myRequest.GetResponse();
                string cookieheader = myRequest.CookieContainer.GetCookieHeader(new Uri(url));
                m_Cookie.SetCookies(new Uri(url), cookieheader);
                sRead = new StreamReader(myResponse.GetResponseStream(), System.Text.Encoding.GetEncoding("UTF-8"));
                html = sRead.ReadToEnd();

                ResponseUri = myResponse.ResponseUri;
            }
            catch (Exception ex)
            {
                html = "";
                return ex.Message;
            }
            finally
            {
                if (sRead != null)
                    sRead.Close();

                if (reqStream != null)
                    reqStream.Close();

                if (myResponse != null)
                    myResponse.Close();

                if (myRequest != null)
                    myRequest.Abort();
            }
            return "";

        }

        public static string RequsetGet(string url)
        {
            string html = string.Empty;
            RequsetGet(url, out html);
            return html;
        }

        public static Stream GetReposeStream(string url, out string msg)
        {
            msg = "";
            Stream stream = null;
            HttpWebRequest myRequest = null;
            HttpWebResponse myResponse = null;
            try
            {
                //构造Web请求
                if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase))
                {
                    ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
                    myRequest = WebRequest.Create(url) as HttpWebRequest;
                    myRequest.ProtocolVersion = HttpVersion.Version10;
                }
                else
                    myRequest = (HttpWebRequest)WebRequest.Create(url);


                myRequest.Method = "GET";
                myRequest.CookieContainer = m_Cookie;
                myResponse = (HttpWebResponse)myRequest.GetResponse();
                string cookieheader = myRequest.CookieContainer.GetCookieHeader(new Uri(url));
                m_Cookie.SetCookies(new Uri(url), cookieheader);
                stream = myResponse.GetResponseStream();
            }
            catch (Exception ex)
            {
                msg = ex.Message;
            }
            return stream;
        }

        public static string RequestBaiDu(string url, string param, System.Text.Encoding encoding, out string html)
        {
            HttpWebRequest myRequest = null;
            HttpWebResponse myResponse = null;
            Stream reqStream = null;
            StreamReader sRead = null;

            byte[] data = System.Text.Encoding.Default.GetBytes(param);
            try
            {
                //构造Web请求
                if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase))
                {
                    ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
                    myRequest = WebRequest.Create(url) as HttpWebRequest;
                    myRequest.ProtocolVersion = HttpVersion.Version10;
                }
                else
                    myRequest = (HttpWebRequest)WebRequest.Create(url);

                myRequest.Method = "POST";
                //myRequest.KeepAlive = true;
                myRequest.ContentType = "application/x-www-form-urlencoded";
                myRequest.ContentLength = data.Length;
                myRequest.Timeout = 10000;
                myRequest.Referer = Referer;
                myRequest.UserAgent = "Mozilla/5.0 (Windows NT 5.2) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.97 Safari/537.11";
                //myRequest.Headers.Add("Accept-Language", "zh-cn");

                if (m_Cookie == null)
                    m_Cookie = new CookieContainer();
                if (Credentials == null)
                    Credentials = CredentialCache.DefaultCredentials;

                myRequest.CookieContainer = m_Cookie;
                myRequest.Credentials = Credentials;
               // myRequest.ServicePoint.Expect100Continue = false;
                //请求流,发送POST参数
                if (data.Length > 0)
                {
                    reqStream = myRequest.GetRequestStream();
                    reqStream.Write(data, 0, data.Length);
                    reqStream.Close();
                }
                //响应流
                myResponse = (HttpWebResponse)myRequest.GetResponse();
                sRead = new StreamReader(myResponse.GetResponseStream(), encoding);
                html = sRead.ReadToEnd();
            }
            catch (Exception ex)
            {
                html = ex.Message;
                return ex.Message;
            }
            finally
            {
                if (sRead != null)
                    sRead.Close();

                if (reqStream != null)
                    reqStream.Close();

                if (myResponse != null)
                    myResponse.Close();

                if (myRequest != null)
                    myRequest.Abort();
            }
            return "";
        }

        private static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
        {
            return true; //总是接受 
        }
    }
}